<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="title" width="650px" destroyOnClose showFooter>
    <!-- <BasicForm @register="registerForm"/> -->
    <BasicTree
      ref="treeRef"
      checkable
      toolbar
      :treeData="state.treeData"
      :checkedKeys="state.checkedKeys"
      :selectedKeys="state.selectedKeys"
      :clickRowToExpand="false"
      search
      :defaultExpandLevel="2"
      title="所拥有的权限"
      @check="onCheck"
      @select="onTreeNodeSelect"
      >
      <template #title={slotTitle,ruleFlag}>
        {{ slotTitle }}
        <Icon v-if="ruleFlag" icon="ant-design:align-left-outlined" style="margin-left:5px;color: red;"></Icon>
      </template>
    </BasicTree>
    
    <!--右下角按钮-->
    <template #footer>
      <PopConfirmButton title="确定放弃编辑？" @confirm="closeDrawer" okText="确定" cancelText="取消">取消</PopConfirmButton>
      <a-button @click="handleSubmit(false)" type="primary" :loading="loading" ghost style="margin-right: 0.8rem">仅保存</a-button>
      <a-button @click="handleSubmit(true)" type="primary" :loading="loading">保存并关闭</a-button>
    </template>
    <RoleDataRuleDrawer @register="registerDrawer1"/>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import {ref, computed, unref, onMounted, toRaw } from 'vue';
  import {BasicDrawer, useDrawer, useDrawerInner} from '/@/components/Drawer';
  import {BasicTree, TreeItem, TreeActionType} from '/@/components/Tree';
  import {BasicForm, useForm} from '/@/components/Form/index';
  import {PopConfirmButton} from '/@/components/Button';
  import RoleDataRuleDrawer from './RoleDataRuleDrawer.vue';
  import { listPermissionTree } from '/@/views/system/menu/menu.api'
  import { queryRolePermission, saveRolePermission} from '/@/api/sys/role';
  // import { listScene } from '/@/views/system/menu/scene/scene.api';
  import { formRolePermissionSchema } from '../role.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Icon } from '/@/components/Icon';

  const { createMessage } = useMessage();
  //表单配置
  const [registerForm, {setProps, resetFields, setFieldsValue, validate, updateSchema}] = useForm({
    labelWidth: 80,
    labelCol: {
      md: { span: 4 },
      sm: { span: 6 },
    },
    wrapperCol: {
      md: { span: 20 },
      sm: { span: 18 },
    },
    schemas: formRolePermissionSchema,
    showActionButtonGroup: false,
  });

  const emit = defineEmits(['register']);
  
  interface State {
    // 树的信息
    treeData: TreeItem[];
    // 树的全部节点信息
    allTreeKeys: any[];
    //树的选择节点信息
    checkedKeys: any[];
    halfCheckedKeys: any[];
    defaultCheckedKeys: any[];
      //树的选中的节点信息
    selectedKeys: any[];
    roleId: string;
    record: any
  }

  const state = ref<State>({
    treeData: [],
    allTreeKeys: [],
    checkedKeys: [],
    halfCheckedKeys: [],
    defaultCheckedKeys: [],
    selectedKeys: [],
    roleId: '',
    record: {}
  })
  const stateValue = state.value
  const title = computed(() => `菜单授权 【${state.value.record.roleName}】`)
  //树的实例
  const treeRef = ref<TreeActionType>();
  const loading = ref(false);

  const [registerDrawer1, {openDrawer:openDataRuleDrawer}] = useDrawer();
  const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
    await reset();
    setDrawerProps({confirmLoading: false,loading:true});
    stateValue.roleId = data.roleId;
    stateValue.record = data;

    //初始化角色菜单数据
    const roleResult = await listPermissionTree({});
    stateValue.treeData = roleResult.treeList;
    stateValue.allTreeKeys = roleResult.menuList.map(e => e.id)

    const permResult = await queryRolePermission({roleId: stateValue.roleId});
    stateValue.checkedKeys = permResult.map(e => e.menuId);
    stateValue.defaultCheckedKeys = permResult.map(e => e.menuId);

    setDrawerProps({loading:false});
  });

  /**
   * 点击选中
   */
  function onCheck(o) {
    stateValue.halfCheckedKeys = treeRef.value?.getHalfCheckedKeys() || []
    stateValue.checkedKeys = o.checked ? o.checked : o
  }

  function onTreeNodeSelect(key) {
    if(key && key.length>0){
      stateValue.selectedKeys = key
    }
    const menuId = toRaw(stateValue.selectedKeys)[0]
    openDataRuleDrawer(true,{functionId: menuId, roleId: toRaw(stateValue.roleId)})
  }
 
  function reset() {
    stateValue.treeData = [];
    stateValue.allTreeKeys = [];
    stateValue.checkedKeys = [];
    stateValue.defaultCheckedKeys = [];
    stateValue.selectedKeys = [];
    stateValue.roleId = '';
  }

  function getTree() {
    const tree = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }

  async function handleSubmit(exit) {
    const { roleId} = unref(state)
        
    let params = {
      roleId,
      // @ts-ignore
      permissionIds: toRaw(treeRef.value?.getCheckedKeys()).join(","),
      lastPermissionIds: toRaw(stateValue.defaultCheckedKeys).join(","),
    };

    loading.value = true;
    await saveRolePermission(params);
    loading.value = false;
    exit && closeDrawer()
    createMessage.success("授权成功")
  }
</script>
